<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\WechatApi\WechatApiOffiAccount;
use App\Services\WechatService;
use App\Services\WxConfigService;
use App\Services\WxMaterialService;
use App\Services\WxMenuService;
use App\Services\WxReplyService;
use Illuminate\Http\Request;

class WxController extends Controller
{
    public function cb($appid)
    {
        if (empty($appid)) {
            exit;
        }

        $wxInfo = WxConfigService::getInstance()->one($appid);
        if (empty($wxInfo)) {
            exit;
        }

        $postStr = file_get_contents('php://input');
        if (empty($postStr)) {
            echo $_GET['echostr'] ?? '';
            exit;
        }

        $post           = fromXml($postStr);
        $from_user_name = $post['FromUserName'] ?? '';       //发送方账号
        $to_user_name   = $post['ToUserName'] ?? '';         //开发者微信号
        $create_time    = $post['CreateTime'] ?? '';         //消息创建时间
        $msg_type       = $post['MsgType'] ?? '';            //消息类型
        $event          = strtolower($post['Event'] ?? '');  //事件类型

        if ($msg_type == 'text') {
            $content = trim($post['Content'] ?? '');         //文本消息内容
            $reply   = WxReplyService::getInstance()->getTextReply($appid, $content);
            if (!$reply) {
                $reply = WxReplyService::getInstance()->getCommonReply($appid);  //找不到关键值获取通用回复
                if (!$reply) {
                    exit;
                }
            }

            $func = $reply->reply_msg_type . 'Reply';
            return $this->$func($from_user_name, $to_user_name, $reply->reply_content);
        } elseif ($msg_type == 'event') {
            $event_key = $post['EventKey'] ?? '';  //事件KEY值
            $reply = WxReplyService::getInstance()->getEventReply($appid, $event, $event_key);
            if ($reply) {
                $func = $reply->reply_msg_type . 'Reply';
                return $this->$func($from_user_name, $to_user_name, $reply->reply_content);
            }
        } else {
        }
        return;
    }

    /**
     * 推送文本消息
     * @param $ToUserName
     * @param $FromUserName
     * @param $Content
     * @return string
     */
    public function textReply($ToUserName, $FromUserName, $Content)
    {
        $CreateTime = time();
        $textTpl    = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        </xml>";

        return sprintf($textTpl, $ToUserName, $FromUserName, $CreateTime, $Content);
    }

    /**
     * 推送图片
     * @param $ToUserName
     * @param $FromUserName
     * @param $media_id
     * @return string
     */
    public function imageReply($ToUserName, $FromUserName, $media_id)
    {
        $CreateTime = time();
        $textTpl    = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[image]]></MsgType>
                        <Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                        </Image>
                        </xml>";

        return sprintf($textTpl, $ToUserName, $FromUserName, $CreateTime, $media_id);
    }

    /**
     * 推送图文
     * @param $ToUserName
     * @param $FromUserName
     * @param $content
     * @return string
     */
    public function newsReply($ToUserName, $FromUserName, $content)
    {
        $CreateTime = time();
        $textTpl    = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        ";
        $textXml = sprintf($textTpl, $ToUserName, $FromUserName, $CreateTime);

        $textXml .= $content;
        $textXml .= '</xml>';

        return $textXml;
    }


    public function menuCreate($appid)
    {
        $res = WxMenuService::getInstance()->createMenu($appid);
        if ($res != 0) {
            return yqerr($res);
        }

        return yqok();
    }

    public function MaterialBatchGet($appid, Request $request)
    {
        $params = [
            'type'   => $request->input('type'),
            'offset' => $request->input('offset', 0),
            'count'  => $request->input('count', 20),
        ];

        $res = WxMaterialService::getInstance()->batchGetMaterial($appid, $params);
        if (!is_array($res)) {
            return yqerr($res);
        }

        return yqok($res);
    }

    public function qrcodeCreate($appid, Request $request)
    {
        $wx_config = WxConfigService::getInstance()->one($appid);
        if (!$wx_config) {
            return yqerr(7019);
        }
        $access_token = WechatService::getInstance()->getAccessToken($wx_config->appid, $wx_config->secret);
        if (!$access_token) {
            return yqerr(7020);
        }

        $scene_str = $request->input('scene_str');
        $url = WechatApiOffiAccount::getInstance()->createQrcode($access_token, $scene_str);
        if (empty($url)) {
            return yqerr(6038);
        }

        return yqok(['url' => $url]);
    }
}
